<?php 
 
namespace App\Http\Controllers\Admin; 
 
use App\Http\Controllers\Controller; 
use Illuminate\Http\Response;
use Illuminate\Http\Request;
use App\Http\Requests\AdminRequest;
use App\Role;
use App\Permission;
use App\Admin;
use DB;
use Config;

class AdminController extends Controller 
{ 
    /** 
     * Create a new controller instance. 
     * 
     * @return void 
     */ 
    const model="PersonnelManagement";
    //
    public function __construct(){
        $this->model=self::model;
        
    }

    public function index() 
    { 

        return view('admin.index.index',['model'=>'']);
    }

    public function user() 
    {   
        
        auth()->guard('admin')->user()->ability('superadmin', 'user.index'); // 建议用这个
        $user=Admin::orderBy('id','desc')->paginate(15);
        return view('admin.user.index',['model'=>$this->model,'user'=>$user]);
    }

    public function create() 
    { 
        $role=Role::get();
        return view('admin.user.create',['model'=>$this->model,'role'=>$role]);
    }

    public function store(AdminRequest $request){

        $role=$request->input('role');
        $data=$request->intersect('name','email','password');

        try {
            DB::beginTransaction();
            $admin=$this->createAdmin($data);
            $admin->attachRole($role);
            //$admin->roles()->attach($role); //只需传递id即可
        } catch (Exception $e) {  
            DB::rollBack();  
            return   parent::error('error');
        }

        DB::commit();
        return parent::success('success',route('admin.user.index'));

    }

    public function edit($id){
        $admin=Admin::with('roles')->find($id);
        $role=Role::get();
        return view('admin.user.edit',['model'=>$this->model,'role'=>$role,'admin'=>$admin]);
    }


    public function update(Request $request){
        $role=$request->input('role');
        $id=$request->input('id');
        $data=$request->intersect('name','email','password');
        
        try {

            DB::beginTransaction();
            $this->updateAdmin($data,$id);
            $admin=Admin::find($id)->roles()->sync($role);

        } catch (Exception $e) { 
            DB::rollBack();    
            return   parent::error('error');
        }
        DB::commit();
        return parent::success('success',route('admin.user.index'));
    }


    protected function createAdmin(array $data)
    {
        return Admin::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }

    protected function updateAdmin(array $data,$id)
    {
        return Admin::where('id',$id)->update([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }
}
